package logic

import (
	"community/models/mysqlinit"
	"community/models/redisinit"
	"community/pkg"
	"context"
	"fmt"

	"community/communityrpc/communityrpc"
	"community/communityrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RetrieveLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRetrieveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RetrieveLogic {
	return &RetrieveLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RetrieveLogic) Retrieve(in *communityrpc.RetrieveRequest) (*communityrpc.RetrieveResponse, error) {
	// todo: add your logic here and delete this line
	var user mysqlinit.User

	mysqlinit.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请重新输入")
	}
	if in.Password != "" {
		if user.Password != pkg.Md5pass(in.Password) {
			return nil, fmt.Errorf("旧密码输入错误，无法进行接下来的操作")
		}
		if user.Password == pkg.Md5pass(in.NewPassword) {
			return nil, fmt.Errorf("新旧密码一致，请重新输入")
		}

		if in.NewPassword != in.ConfirmPassword {
			return nil, fmt.Errorf("修改的两次密码不一致，请重新输入")
		}
		user.Password = pkg.Md5pass(in.NewPassword)

	} else {
		result, _ := redisinit.Client.Get("SendSms" + in.Account + "Retrieve").Result()
		if in.SendSms != result {
			return nil, fmt.Errorf("短信验证码错误，请重新输入")
		}
		user.Password = pkg.Md5pass(in.SendPassword)

	}

	mysqlinit.DB.Debug().Updates(&user)
	return &communityrpc.RetrieveResponse{
		Id: int64(user.ID),
	}, nil
}
